#include "plc_debug.h"

#include <STM32FreeRTOS.h>
// #ifdef PLC
#include "softplc.h"
// #endif
#include <core_debug.h>
#include "hwboard.h"

#ifdef MONITOR_NET
EthernetServer server(8080);
#endif

plc_debug debugger;
extern char debug_buffer[];


#ifdef MONITOR_SERIAL
SLIPPacketSerial myPacketSerial;
#endif


#define BUFFER_FREE 0
#define BUFFER_BUSY 1
#if defined(PLC) || defined(RTE_APP)
//  long buffer_state = BUFFER_FREE;
extern unsigned long __tick;
extern unsigned int sizeof_dbgvardsc;

#endif

int system_cmd(const u8 *rx, int rxlen, u8 *tx, int txlen);

#ifdef MONITOR_SERIAL
void onPacketReceived(const uint8_t *buffer, size_t size)
{
    if (size)
    {
        int txlen = system_cmd(buffer, size, debugger.txbuf, sizeof(debugger.txbuf));
        if (txlen > 0)
        {
            myPacketSerial.send(debugger.txbuf, txlen);
        }
    }
}
#endif
osThreadId dbg_thd;
void thd(void const *arg)
{
    debugger.thread_run();
}
void plc_debug::begin()
{
#ifdef MONITOR_NET
    server.begin();
#endif
#ifdef MONITOR_SERIAL
    myPacketSerial.begin(115200);
    myPacketSerial.setPacketHandler(&onPacketReceived);
#endif
    osThreadDef(dbg_thd, &thd, osPriorityNormal, 0, 512);
    dbg_thd = osThreadCreate(osThread(dbg_thd), NULL);
}

void plc_debug::thread_run()
{
    while (1)
    {
#ifdef MONITOR_NET
        EthernetClient client = server.available();
        if (client)
        {
            bool currentLineIsBlank = true;
            while (client.connected())
            {
                while (client.available())
                {
                    int len = client.read(rxbuf, sizeof(rxbuf));
                    if (len > 0)
                    {
                        int txlen = system_cmd(rxbuf, len, txbuf, sizeof(txbuf));
                        if (txlen > 0)
                        {
                            client.write(txbuf, txlen);
                        }
                    }
                    else
                    {
                        vTaskDelay(1);
                    }
                }
            }
        }
        vTaskDelay(1);
        client.stop();
#endif
#ifdef MONITOR_SERIAL
        myPacketSerial.update();
        if (myPacketSerial.overflow())
        {
        }
        vTaskDelay(10);
#endif
        vTaskDelay(1);
    }
}


void plc_debug_init()
{
    debugger.begin();
}
